package com.xjrsoft.module.desktop.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.EnabledMark;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.page.ListInput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.desktop.dto.SetDesktopRelationDto;
import com.xjrsoft.module.desktop.entity.DesktopRelation;
import com.xjrsoft.module.desktop.entity.DesktopSchema;
import com.xjrsoft.module.desktop.service.IDesktopRelationService;
import com.xjrsoft.module.desktop.service.IDesktopSchemaService;
import com.xjrsoft.module.desktop.vo.DesktopSchemaVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 桌面设计授权表 前端控制器
 * </p>
 *
 * @author tzx
 * @since 2023-06-01
 */
@RestController
@RequestMapping(GlobalConstant.DESKTOP_MODULE_PREFIX + "/relation")
@Api(value = GlobalConstant.SYSTEM_MODULE_PREFIX + "/relation", tags = "桌面设计权限接口")
@AllArgsConstructor
public class DesktopRelationController {

    private final IDesktopRelationService relationService;

    private final IDesktopSchemaService desktopSchemaService;

    @GetMapping(value = "/role")
    @ApiOperation(value = "查询角色授权的桌面设计")
    public R getRelationsOfRole(@RequestParam Long roleId) {
        List<DesktopRelation> relationList = relationService.list(Wrappers.lambdaQuery(DesktopRelation.class)
                .eq(DesktopRelation::getRoleId, roleId));
        if (CollectionUtils.isNotEmpty(relationList)) {
            Set<Long> desktopIdList = relationList.stream().map(DesktopRelation::getDesktopId).collect(Collectors.toSet());
            List<DesktopSchema> desktopSchemaList = desktopSchemaService.list(Wrappers.lambdaQuery(DesktopSchema.class)
                    .select(DesktopSchema.class, x -> VoToColumnUtil.fieldsToColumns(DesktopSchemaVo.class).contains(x.getProperty()))
                    .in(DesktopSchema::getId, desktopIdList)
                    .eq(DesktopSchema::getEnabledMark, EnabledMark.ENABLED.getCode()));
            return R.ok(BeanUtil.copyToList(desktopSchemaList, DesktopSchemaVo.class));
        }
        return R.ok();
    }

    @PostMapping
    @ApiOperation(value = "保存角色的桌面设计权限")
    @Transactional
    public R add(@Valid @RequestBody SetDesktopRelationDto dto) {
        Long roleId = dto.getRoleId();
        // 先删除角色的权限
        relationService.remove(Wrappers.<DesktopRelation>query().lambda().eq(DesktopRelation::getRoleId, roleId));
        List<Long> desktopIds = dto.getDesktopIds();
        if (CollectionUtils.isNotEmpty(desktopIds)) {
            List<DesktopRelation> toSaveList = new ArrayList<>(desktopIds.size());
            for (Long desktopId : desktopIds) {
                DesktopRelation relation = new DesktopRelation();
                relation.setRoleId(roleId);
                relation.setDesktopId(desktopId);
                toSaveList.add(relation);
            }
            relationService.saveBatch(toSaveList);
        }
        return R.ok();
    }

    @GetMapping(value = "/current-desktops")
    @ApiOperation(value = "查询当前用户拥有权限的桌面设计")
    public R getDesktopsOfCurrentUser(ListInput dto) {
        List<DesktopSchemaVo> resultList = new ArrayList<>();
        // 查询默认首页
        DesktopSchema firstDesktop = desktopSchemaService.getOne(Wrappers.lambdaQuery(DesktopSchema.class)
                .eq(DesktopSchema::getIsFirst, YesOrNoEnum.YES.getCode())
                .select(DesktopSchema.class, x -> VoToColumnUtil.fieldsToColumns(DesktopSchemaVo.class).contains(x.getProperty())));
        if (firstDesktop != null&&StrUtil.isBlank(dto.getKeyword())) {//当搜索关键字为空时将默认首页添加进去
            resultList.add(BeanUtil.toBean(firstDesktop, DesktopSchemaVo.class));
        }
        // 查询授权的桌面设计
        List<Long> currentRoleIdList = StpUtil.getTokenSession().get(GlobalConstant.LOGIN_USER_ROLE_ID_KEY, new ArrayList<>());
        List<DesktopRelation> desktopRelationList = relationService.list(
                Wrappers.lambdaQuery(DesktopRelation.class).in(DesktopRelation::getRoleId, currentRoleIdList));
        if (CollectionUtils.isNotEmpty(desktopRelationList)) {
            Set<Long> desktopIdList = desktopRelationList.stream().map(DesktopRelation::getDesktopId).collect(Collectors.toSet());
            List<DesktopSchema> desktopSchemaList = desktopSchemaService.list(Wrappers.lambdaQuery(DesktopSchema.class)
                    .select(DesktopSchema.class, x -> VoToColumnUtil.fieldsToColumns(DesktopSchemaVo.class).contains(x.getProperty()))
                    .in(DesktopSchema::getId, desktopIdList)
                    .eq(DesktopSchema::getEnabledMark, EnabledMark.ENABLED.getCode())
                    .like(StrUtil.isNotBlank(dto.getKeyword()), DesktopSchema::getName, dto.getKeyword()));
            resultList.addAll(BeanUtil.copyToList(desktopSchemaList, DesktopSchemaVo.class));
        }
        List<DesktopSchemaVo> collect = resultList.stream().distinct().collect(Collectors.toList());//去重操作，防止默认首页出现两次
        return R.ok(collect);
    }
}
